package com.altekis.kanbankaze.server;

import java.util.List;

import com.altekis.kanbankaze.client.UserAccountService;
import com.altekis.kanbankaze.server.dao.UserAccountDAO;
import com.altekis.kanbankaze.shared.UserAccount;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.inject.Inject;

/**
 * The server side implementation of the {@link User} RPC service.
 * 
 * @author lordkhizir
 * 
 */
public class UserAccountServiceImpl implements UserAccountService {
	
		final static public UserService userService = UserServiceFactory.getUserService();
		
		static public UserAccount mkUserAccount(User user){
			UserAccount userAccount = new UserAccount();
			userAccount.setLogin(user.getEmail());
			userAccount.setId(user.getUserId());
			userAccount.setName(user.getNickname());
			return userAccount;
		}

		private final UserAccountDAO userAccountDAO;
		
		@Inject
		public UserAccountServiceImpl(UserAccountDAO userAccountDAO) {
			this.userAccountDAO = userAccountDAO;
		}
		
		@Override
		public UserAccount createChannelForCurrentUser() {
			// TODO Perform login
			// If logged ok, create a Channel for the user
			UserAccount user = getCurrentUser();
			String channelId = null;
			if (user!=null) {
				channelId = ChannelServer.createChannel(user.getLogin());
				user.setChannelId(channelId);
				TemporaryRepository.users.add(user); // TODO All this has to be serialized, as GAE doesn't guarantee the same instance between requests
				userAccountDAO.save(user);
			}
			return user;
		}
		@Override
		public String createLoginURL(String callbackUrl) {
			return userService.createLoginURL(callbackUrl);
		}
		@Override
		public String createLoginURL(String callbackUrl, String authDomain) {
			return userService.createLoginURL(callbackUrl, authDomain);
		}
		@Override
		public String createLogoutURL(String callbackUrl) {
			return userService.createLogoutURL(callbackUrl);
		}
		@Override
		public String createLogoutURL(String destinationURL, String authDomain) {
			return userService.createLogoutURL(destinationURL, authDomain);
		}

		@Override
		public List<UserAccount> findAll() {
			return userAccountDAO.findAll();
		}
		
		@Override
		public UserAccount findById(String id) {
			return userAccountDAO.findById(id);
		}
		
		@Override
		public UserAccount getCurrentUser() {
			User loggedUser = userService.getCurrentUser();
			UserAccount userAccount = null;
			if (loggedUser!=null) {
				userAccount = mkUserAccount(loggedUser); 
			}
			return userAccount;
		}
		
		@Override
		public boolean isUserAdmin() {
			return userService.isUserAdmin();
		}
		@Override
		public boolean isUserLoggedIn() {
			return userService.isUserLoggedIn();
		}
		@Override
		public UserAccount save(UserAccount userAccount) {
			return userAccountDAO.save(userAccount);
		}
	}
